<template>
  <el-dialog v-model="dialogVisible" title="搜索设备" width="50%">
    <avue-crud
      ref="avueRef"
      v-model:search="search"
      :page="page"
      :data="pageData?.data"
      :option="option"
      :table-loading="loading"
      @selection-change="selectionChange"
      @search-change="searchChange"
      @search-reset="searchChange"
      @current-change="currentChange"
      @refresh-change="handleQuery"
    />

    <template v-if="selectSnList.length" #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onConfirmClick">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import DeviceAPI from "@/api/device";
import { UserDeviceModel } from "@/model/user-device-model";
import { PageDataModel } from "@/model/page-data-model";
import options, { UserWithDeviceSearchModel } from "./avue-options";

defineOptions({
  name: "UserWithDeviceSearchDialog",
});
const avueRef = ref();
const emits = defineEmits(["choosed"]);
const dialogVisible = ref(false);
const option = ref(options);
const pageData = ref<PageDataModel<UserDeviceModel>>();
const loading = ref(false);
const selectSnList = ref<string[]>([]);
const search = ref<UserWithDeviceSearchModel>({
  filter_device_sn: "",
  page: 1,
});

const page = computed(() => {
  return {
    ...pageData.value,
    layout: "total, prev, pager, next, jumper",
  };
});

// 查询
async function handleQuery() {
  loading.value = true;
  DeviceAPI.userWithDeviceUnbind(search.value)
    .then((res: any) => {
      pageData.value = res;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * @description 分页切换
 * @param val  当前页码
 */
function currentChange(val: number) {
  search.value.page = val;
  handleQuery();
}

// 选择改变
function selectionChange(selection: any) {
  selectSnList.value = selection.map((item: any) => item.device_sn);
}

/**
 * 处理搜索变化的函数
 * 当搜索条件变化时，此函数会被调用，通常用于处理搜索前的准备工作和搜索完成后的回调
 *
 * @param {Object} params - 包含搜索条件的参数对象
 * @param {Function} done - 一个回调函数，用于通知搜索操作完成
 */
function searchChange(params: any, done: Function) {
  search.value.filter_device_sn = params.device_sn;
  handleQuery().then(() => {
    done();
  });
}

/**
 * @description 确定按钮点击事件
 */
function onConfirmClick() {
  emits("choosed", selectSnList.value);
  dialogVisible.value = false;
  avueRef.value.clearSelection();
}

const open = () => (dialogVisible.value = true);

// 导出组件实例类型
export interface UserWithDeviceSearchDialogInstance {
  open: () => void;
}

defineExpose({
  open,
});
</script>
